package cn.lixu.searchMaster.service.impl;

import cn.lixu.basic.exception.BusinessException;
import cn.lixu.basic.service.impl.BaseServiceImpl;
import cn.lixu.basic.util.*;
import cn.lixu.order.domain.OrderPetAcquisition;
import cn.lixu.order.mapper.OrderPetAcquisitionMapper;
import cn.lixu.org.domain.Employee;
import cn.lixu.org.domain.Shop;
import cn.lixu.org.mapper.EmployeeMapper;
import cn.lixu.org.mapper.ShopMapper;
import cn.lixu.pet.domain.Pet;
import cn.lixu.pet.mapper.PetMapper;
import cn.lixu.searchMaster.domain.SearchMasterMsg;
import cn.lixu.searchMaster.domain.SearchMasterMsgAuditLog;
import cn.lixu.searchMaster.dto.AccpetDto;
import cn.lixu.searchMaster.mapper.SearchMasterMsgAuditLogMapper;
import cn.lixu.searchMaster.mapper.SearchMasterMsgMapper;
import cn.lixu.searchMaster.query.SearchMasterMsgQuery;
import cn.lixu.searchMaster.service.ISearchMasterMsgService;
import cn.lixu.user.domain.User;
import cn.lixu.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     * 发布寻主消息
     *
     * @param smm
     * @param id
     */
    @Override
    public void publish(SearchMasterMsg smm, Long id) {
        //1.首先保存在t_search_master_msg
        //通过logininfo查询user信息
        User user = userMapper.loadByLogininfoId(id);
        smm.setUser_id(user.getId());

        //shop_id 先计算最近的店铺信息
        //获取当前地址的point
        Point point = DistanceUtils.getPoint(smm.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShop_id(nearestShop.getId());
        searchMasterMsgMapper.save(smm);

        //审核
        Boolean textCensor = BaiduAuditUtils.TextCensor(smm.getName() + smm.getAddress() + smm.getTitle());//文本
        String resources = smm.getResources();
        Boolean imgCensor = true;
        if (resources != null) {
            imgCensor = BaiduAuditUtils.ImgCensor(smm.getResources()); //图片
        }
        if (textCensor && imgCensor) {//审核通过
            //1.修改状态
            smm.setState(1);
            smm.setNote("审核成功");
            searchMasterMsgMapper.update(smm);

            //2.添加日志文件
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setState(1);
            auditLog.setNote("审核成功");
            auditLog.setAudit_time(new Date());
            auditLog.setMsg_id(smm.getId());
            searchMasterMsgAuditLogMapper.save(auditLog);
        } else {

            //1.修改状态
            smm.setNote("审核失败，请重新输入信息");
            searchMasterMsgMapper.update(smm);

            //2.添加日志文件
            SearchMasterMsgAuditLog auditLog = new SearchMasterMsgAuditLog();
            auditLog.setState(0);
            auditLog.setNote("审核失败，请重新输入信息");
            auditLog.setAudit_time(new Date());
            auditLog.setMsg_id(smm.getId());
            searchMasterMsgAuditLogMapper.save(auditLog);
            throw new BusinessException("信息异常，请重新输入");
        }
    }

    /**
     * 待处理状态
     *
     * @param searchMasterMsgQuery
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery searchMasterMsgQuery, Long id) {
        Employee employee = employeeMapper.loadByLogininfoId(id);
        searchMasterMsgQuery.setState(1);
        if (employee.getShop_id() != null) {
            searchMasterMsgQuery.setShopId(employee.getShop_id());
        }
        return super.queryPage(searchMasterMsgQuery);
    }

    /**
     * 用户处理状态
     *
     * @param searchMasterMsgQuery
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery searchMasterMsgQuery, Long id) {
        // 查询到用户id
        User user = userMapper.loadByLogininfoId(id);
        searchMasterMsgQuery.setUserId(user.getId());  // <if userId！=null> and user_id=#{userId}<>
        return super.queryPage(searchMasterMsgQuery);
    }

    /**
     * 拒单
     *
     * @param id
     */
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     *
     * @param dto
     * @param id
     */
    @Override
    public void accept(AccpetDto dto, Long id) {
        //寻主发布人ID
        Long msgId = dto.getMsgId();
        //处理人ID
        Long handler = dto.getHandler();
        //备注
        String note = dto.getNote();
        //根据msgId查询订单，如果存在，说明该订单正在处理中，查不到就说明该订单被拒接或者直接放在寻主池里面了
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (order != null) {//之前已经接单了
            throw new BusinessException("订单正在处理之中，请稍候再试");
        }
        //1.生成一个pet【根据msgId生成】
        //通过msgId生成一个SearchMasterMsg对象
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        //通过SearchMasterMsg对象生成一个Pet对象
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        //保存
        petMapper.save(pet);

        //2.生成一个订单
        OrderPetAcquisition opa = ininOrderPetAcquisition(dto, pet, searchMasterMsg);
        //3.保存订单
        orderPetAcquisitionMapper.save(opa);
    }

    /**
     * 生成一个订单对象
     *
     * @param dto
     * @param pet
     * @param smm
     * @return
     */
    private OrderPetAcquisition ininOrderPetAcquisition(AccpetDto dto, Pet pet, SearchMasterMsg smm) {
// 创建一个订单对象，赋值
        OrderPetAcquisition order = new OrderPetAcquisition();

        // 随机生成一个订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getUser_id()));
        // 摘要
        order.setDigest("【" + smm.getTitle() + "】");
        // 最后确认时间 定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000));

        order.setState(0);// 待处理
        order.setPrice(smm.getPrice());
        order.setPet_id(pet.getId());
        order.setUser_id(smm.getUser_id());
        order.setShop_id(smm.getShop_id());
        order.setAddress(smm.getAddress());
        order.setEmp_id(dto.getHandler());
        order.setSearch_master_msg_id(dto.getMsgId());
        return order;
    }


    /**
     * 通过msgId生成一个SearchMasterMsg对象
     *
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShop_id());
        pet.setSearch_master_msg_id(smm.getId());
        //这里不能对userId进行赋值，因为这里的user是购买者的ID，而不是员工的ID
        return pet;
    }


}

